package com.jason.basicandroid.contentprovider;

import java.util.LinkedList;
import java.util.List;

import com.jason.basicandroid.contentprovider.BookProviderMetaData.BookTableMetaData;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class ContentProviderDemo extends ListActivity {
	private ListAdapter adapter = null;
    Menu myMenu = null;
    ListView myListView = null;
	ContentResolver myContentResolver = null;
    static final private int ACTIVITY_ADD_BOOK = 0;
    static final private int ACTIVITY_EDIT_BOOK = 1;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        myContentResolver = getContentResolver();
        Cursor c = myContentResolver.query(
        		BookTableMetaData.CONTENT_URI, null, null, null, null);
        startManagingCursor(c);
        
        String[] cols = new String[]{BookTableMetaData.BOOK_NAME};
        int[] names = new int[]{R.id.row_tv};
        adapter = new SimpleCursorAdapter(this, R.layout.list_item, c, cols, names);
        setListAdapter(adapter);
        
        myListView = getListView();
        myListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);        
        myListView.setOnItemLongClickListener(new ItemLongClickListener(this));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        
        myMenu = menu;
        
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        Intent nextIntent = null;
        
        switch(id) {
        case R.id.menuAdd:
            nextIntent = new Intent(this, BookEditor.class);
            startActivityForResult(nextIntent, ACTIVITY_ADD_BOOK);
            
            break;

        case R.id.menuDelete:
        	long[] ids = myListView.getCheckedItemIds();
        	StringBuilder strWhereIn = new StringBuilder("_id IN (");
        	for(int i = 0; i < ids.length; ++i) {
        		strWhereIn.append(ids[i]);
        		strWhereIn.append(",");
        	}
        	strWhereIn.deleteCharAt(strWhereIn.length() - 1);
    		strWhereIn.append(")");
    		myContentResolver.delete(BookTableMetaData.CONTENT_URI, strWhereIn.toString(), null);
    		
            break;
 
	    default:
	    	return super.onOptionsItemSelected(item);
        }
        
		myListView.clearChoices();
                
        return true;
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {    
    	String strName = null;
    	String strAuthor = null;
    	String strISBN = null;
    	ContentValues contentValues = null;
    	long curDate = System.currentTimeMillis();

        if(resultCode == RESULT_OK) {
        	strName = data.getStringExtra(BookTableMetaData.BOOK_NAME);
        	strAuthor = data.getStringExtra(BookTableMetaData.BOOK_AUTHOR);
        	strISBN = data.getStringExtra(BookTableMetaData.BOOK_ISBN);

        	contentValues = new ContentValues();
        	contentValues.put(BookTableMetaData.BOOK_NAME, strName);
        	contentValues.put(BookTableMetaData.BOOK_AUTHOR, strAuthor);
        	contentValues.put(BookTableMetaData.BOOK_ISBN, strISBN);
        	contentValues.put(BookTableMetaData.MODIFIED_DATE, curDate);        	
        }
            
        switch(requestCode) {
        case ACTIVITY_ADD_BOOK:
        case ACTIVITY_EDIT_BOOK:
            if(resultCode == RESULT_OK) {
            	if(requestCode == ACTIVITY_ADD_BOOK) {
		        	contentValues.put(BookTableMetaData.CREATED_DATE, curDate);  
            		myContentResolver.insert(BookTableMetaData.CONTENT_ITEM_URI, contentValues);        	
            	} else if (requestCode == ACTIVITY_EDIT_BOOK) {
            		Long id = data.getLongExtra(BookTableMetaData.BOOK_ID, -1);
            		if(id != -1) {
                		Uri theBook = Uri.withAppendedPath(BookTableMetaData.CONTENT_ITEM_URI, id.toString());
                		myContentResolver.update(theBook, contentValues, null, null);            		
            		}
            	}
            }
            break;
                
        default:
            break;
        }
    }
    
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
  		super.onListItemClick(l, v, position, id);
    }
    
    private class ItemLongClickListener implements OnItemLongClickListener{
    	private Context context = null;
    	public ItemLongClickListener(Context context) {
    		this.context = context;
    	}
    	@Override
		public boolean onItemLongClick(AdapterView parent, View view, int position, long id) {
            Intent nextIntent = new Intent(context, BookEditor.class);
            nextIntent.putExtra(BookTableMetaData.BOOK_ID, id);        
            startActivityForResult(nextIntent, ACTIVITY_EDIT_BOOK);    
    		return true;
		 }
    }
}